import os
import datetime
import json
from usllib.parse import urlsplit

from mitmproxy import ctx, http

from lib.WeChatArticle.WeChatArticle import WeChatArticle

# 定义json数据存储的的目录和文件名
json_file_path = os.path.dirname(os.path.abspath(__file__))
json_file_name = datetime.datetime.today().strftime("%Y-%m-%d") + '.json'
json_file_abs_path = json_file_path + '/data/json/' + json_file_name
img_abs_path = json_file_path + '/data/img'

# 定义请求标识
json_url_code = "https://mp.weixin.qq.com/mp/profile_ext?action=getmsg"
img_url_code = "http://mmbiz.qpic.cn/mmbiz_jpg"

class WeChat:

    def __init__(self):
        self.img_list = []

    def response(self, flow):
        # print(flow.request.url)
        weChatArticle = WeChatArticle(flow.response.text)
        # json 数据处理
        if flow.request.url.startswith(json_url_code):
            weChatArticle.article(json_file_abs_path)

        # 图片数据处理
        # if flow.request.url.startswith(img_url_code):
        #     # print(flow.response.text)
        #     weChatArticle.save_img(flow.request.url, img_abs_path)

        if flow.response.headers['Content-Type'][0].startswith('image/'):
            url = urlsplit(flow.request.url)
            name = os.path.basename(url.path)
            with open(name, 'wb') as f:
                f.write(flow.response.content)
addons = [
    WeChat()
]
